package com.kaishengit.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import service.UserService;

import com.kaishengit.entity.User;
import com.kaishengit.util.DateTimeUtil;
import com.kaishengit.util.StringUtil;
import com.kaishengit.util.web.ServletUtil;

public class UserLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService service=new UserService();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String state=request.getParameter("state");
		ServletUtil.setRequestAttribute(request, "state", state);
		ServletUtil.forward(request, response, "/login");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String username=req.getParameter("username");
		String password=StringUtil.sha1(req.getParameter("password"));
		
		User user=service.findUserByName(username);
		if(password!=null&&user!=null&&password.equals(user.getPassword())){
			String lastAccessTime=DateTimeUtil.getNow();
			user.setLastAccessTime(lastAccessTime);
			service.update(user);
			
			ServletUtil.getSession(req).setAttribute("user", user);
			
			resp.sendRedirect("userIndex.jspx");
		}else{
			ServletUtil.setRequestAttribute(req, "state", 10002);
			ServletUtil.forward(req, resp, "/login");
		}
	}
}
